//
//  GlobalSettings.m
//  eyeinfo
//
//  Created by kingsoft on 11-1-11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GlobalCls.h"
#import "zlib.h"

@implementation GlobalCls

@synthesize m_strUrl;


+ (NSString*) getHttpData:(NSString*) strUrl
{
	NSURL* url = [NSURL URLWithString:strUrl];
	NSMutableURLRequest* request = [NSMutableURLRequest new];
	[request setURL:url];
	[request setHTTPMethod:@"GET"];
	NSURLResponse* response;
	NSData* data = [NSURLConnection sendSynchronousRequest:request
										 returningResponse:&response error:nil];
	NSString* strRet = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	return strRet;
}

+(NSString*) getStringByCompressUrl:(NSString*) strUrl
{
	NSString* strReturn = @"";
	NSURL* url = [NSURL URLWithString:strUrl];
	NSMutableURLRequest* request = [NSMutableURLRequest new];
	[request setURL:url];
	[request setHTTPMethod:@"GET"];
	NSURLResponse* response;
	NSData* data = [NSURLConnection sendSynchronousRequest:request
										 returningResponse:&response error:nil];
	long uncompressedSize = data.length * 3;
	long dataSize = data.length;
	if (dataSize == 0) {
		return strReturn;
	}
	
	Bytef *buffer[uncompressedSize];
	Bytef *dataSource[dataSize];
	
	[data getBytes:dataSource];
	uLongf ld;
	uLong sl = dataSize;
	ld = (uLong)uncompressedSize;
	if(uncompress((Bytef*)buffer, &ld, (const Bytef*)dataSource, sl) == Z_OK)
	{
		NSData *uncompressedData = [NSData dataWithBytes:buffer length:ld];
		strReturn = [[NSString alloc] initWithData:uncompressedData encoding:NSUTF8StringEncoding];
	}
	return strReturn;
}

+(NSString*) getDocumentDir
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentDirectory = [paths objectAtIndex:0];
	return documentDirectory;
}

+(NSString*) getDocumentFile:(NSString*) strAppendFile
{
	NSString* strDocumentDir = [GlobalCls getDocumentDir];
	NSString *filename = [strDocumentDir stringByAppendingPathComponent:strAppendFile];
	return filename;
}

+(bool)downloadFile:(NSString*) strUrl  saveFile : (NSString*) strFileSavePath
{
	bool bRetCode = FALSE;
	
	NSURL* url = [NSURL URLWithString:strUrl];
	NSMutableURLRequest* request = [NSMutableURLRequest new];
	[request setURL:url];
	[request setHTTPMethod:@"GET"];
	NSURLResponse* response;
	NSData* data = [NSURLConnection sendSynchronousRequest:request
										 returningResponse:&response error:nil];
	NSError * errorFileWrite;
	[data writeToFile:strFileSavePath options:NSDataWritingFileProtectionNone error:&errorFileWrite];
	
	if (!errorFileWrite) 
		bRetCode = TRUE;
	
	return bRetCode;
}

@end
